<template>
  <view class="binding-phone-view">
    <NavbarCustom
      leftIconColor="#333333"
      bgColor="transparent"
      isBack
      :left="{ imageUrl: leftImageUrl, width: '48rpx' }"
    />
    <image :src="backgroundImage" mode="widthFix" class="background"></image>
    <view class="content-view">
      <view class="head">
        <view class="title-view">你好！</view>
        <view class="text-view">欢迎登录E-Selina</view>
      </view>
      <view class="content">
        <view class="label-view">
          <image :src="phoneIcon" mode="" class="label-icon"></image>
          <text class="label-text">手机号</text>
        </view>
        <view class="phone-view">
          <view class="right-view"
            ><up-input
              placeholder-style="color:#B8BFBF"
              border="none"
              placeholder="请输入手机号"
              v-model="form.mobile"
              type="number"
              width="100%"
              maxlength="20"
              clearable
          /></view>
        </view>
        <view class="label-view">
          <image :src="codeIcon" mode="" class="label-icon"></image>
          <text class="label-text">验证码</text>
        </view>
        <view class="code-view">
          <view class="left-view"
            ><up-input
              placeholder-style="color:#B8BFBF"
              border="none"
              placeholder="请输入验证码"
              v-model="form.verifycode"
              type="number"
              maxlength="6"
              clearable
          /></view>
          <view class="middle-view"> </view>
          <view class="right-view">
            <up-code
              keep-running
              unique-key="binding-phone"
              :seconds="seconds"
              @end="end"
              @start="start"
              ref="uCode"
              @change="codeChange"
            ></up-code>
            <text
              :class="{ active: canGetCode }"
              @tap="$u.throttle(handleGetCode, 500)"
              >{{ tips }}</text
            >
          </view>
        </view>
        <view class="bottom-vew" hover-class="u-hover-class">
          <up-button
            :disabled="disabled"
            :customStyle="buttonStyle"
            :loading="loading"
            @click="handleClickSave"
          >
            <view class="button-text">立即绑定</view>
          </up-button>
        </view>
        <view class="quick-title" @click="handleClickAgree">
          <view class="icon-view">
            <view v-if="agree" class="icon-agree"></view>
          </view>
          <view class="agree-text-view">
            登录即代表你同意
            <text class="name-text" @tap.stop="handleClick('protocol')"
              >《用户协议》</text
            >
            <text class="name-text" @tap.stop="handleClick('policy')"
              >《用户隐私协议》</text
            >
          </view>
        </view>
      </view>
    </view>

    <up-toast ref="uToast"></up-toast>
  </view>
</template>

<script setup>
import NavbarCustom from "@/components/navbar-custom/index.vue";
import { ref, reactive, computed, watch, onMounted } from "vue";
import { onLoad, onReady } from "@dcloudio/uni-app";
import { sendCode, userCodeLogin, testEncode } from "@/api/login/index.js";
import { encryptByXOR } from "@/utils/signature.js";
import useUserStore from "@/store/user.js";
import { storeToRefs } from "pinia";
const userStore = useUserStore();
const { userInfo, systemInfo } = storeToRefs(userStore); // 响应式
const leftImageUrl = ref("/static/images/login/loginfanhui@3x.png");
const backgroundImage = ref("/static/images/login/background.png");
const phoneIcon = ref("/static/images/login/shoujihao@3x.png");
const codeIcon = ref("/static/images/login/yanzhengma@3x.png");
const form = reactive({
  type: 3,
  device: systemInfo.value.deviceId,
  areacode: "0086",
  mobile: "",
  verifycode: "",
});
const canGetCode = ref(true);
const seconds = ref(60);
const loading = ref(false);
const params = ref({});
const tips = ref("");
const type = ref("login");
const uCode = ref(null);
const returnUrl = ref("");
const agree = ref(true);
const buttonStyle = reactive({
  height: "98rpx",
  background: "#DCE0E0",
  color: "transparent",
  "border-radius": "59rpx",
});
const disabled = computed(() => {
  return form.verifycode && form.mobile ? false : true;
});
const isPhone = computed(() => {
  return type.value == "phone";
});
watch(disabled, (val) => {
  buttonStyle.background = val
    ? "#DCE0E0"
    : "linear-gradient( 315deg, #43D9F0 0%, #5CE5D5 100%)";
});
onMounted(() => {});
onReady(() => {
  canGetCode.value = uCode.value.canGetCode ? true : false;
});
onLoad((options) => {
  console.log("-----options----", options);
  if (options && options.type) {
    type.value = options.type;
  }
  if (options && options.path) {
    returnUrl.value = decodeURIComponent(decodeURIComponent(options.path));
  }
  if (options) {
    let { unionId } = options;
    if (unionId) {
      params.value = options;
    }
  }
});
const handleClick = (type) => {
  uni.navigateTo({
    animationType: "pop-in",
    url: "/pages/login/agreement/agreement?type=" + type,
  });
};
const handleClickAgree = () => {
  agree.value = !agree.value;
};
const checkAgree = () => {
  if (!agree.value) {
    uni.showToast({
      title: "请阅读并同意《用户协议》和《用户隐私协议》",
      icon: "none",
      duration: 2000,
    });
    return false;
  }
  return true;
};
const handleGetCode = () => {
  if (form.mobile == "") {
    uni.showToast({
      title: "请输入手机号",
      icon: "none",
      duration: 1500,
    });
    return;
  }
  var reg = /^[1][3456789][0-9]{9}$/;
  if (!reg.test(form.mobile)) {
    uni.showToast({
      icon: "none",
      title: "请输入正确的手机号",
    });
    return false;
  }
  startCode();
};
const startCode = () => {
  if (uCode.value.canGetCode) {
    // 模拟向后端请求验证码
    if (uni.$u.platform !== "3") {
      uni.showLoading({
        title: "正在获取验证码",
      });
    } else {
      uni.$u.toast("正在获取验证码");
    }
    getCode();
  }
};
const getCode = async () => {
  try {
    let res = await sendCode({
      type: 4,
      mobile: form.mobile,
      areacode: form.areacode,
      device: form.device,
    });
    if (uni.$u.platform !== "3") {
      uni.hideLoading();
    }
    console.log("getCode", res);
    if (res.code === 0) {
      uni.$u.toast("验证码已发送");
      uCode.value.start();
      console.log("--------发送成功----------");
    } 
	// else {
    //   uni.showToast({
    //     title: "获取验证码失败",
    //     icon: "none",
    //   });
    // }
  } catch (e) {
    console.log(e);
    if (e.msg) {
      uni.showToast({
        title: e.msg,
        icon: "none",
      });
    }
    //TODO handle the exception
    if (uni.$u.platform !== "3") {
      uni.hideLoading();
    }
  }
};
const handleClickSave = () => {
  var reg = /^[1][3456789][0-9]{9}$/;
  if (!reg.test(form.mobile)) {
    uni.showToast({
      icon: "none",
      title: "请输入正确的手机号",
    });
    return false;
  }
  handleBindPhone();
};
const handleBindPhone = async () => {
  if (!checkAgree()) {
    return false;
  }
  try {
    await userStore.Auto_login({
      mobile: form.mobile,
      areacode: form.areacode,
      device: encryptByXOR(form.device), // 异或加密
      verifycode: form.verifycode,
    });
    uni.$emit("index-collection-list")
    if (userInfo.value && userInfo.value.setinfo === "1") {
      uni.redirectTo({
        url: "/pages/login/user-info/user-info",
      });
      return;
    }
    goBackPage();
  } catch (e) {
    //TODO handle the exception
  }
};
const goBackPage = () => {
  console.log("---------绑定成功跳转------");
  let pages = getCurrentPages();
  let len = pages.length;

  if (len && len - 1) {
    let prevPage = pages[len - 1]; //上一个页面

    if (prevPage && prevPage.$vm) {
      prevPage.$vm.isRefresh = true;
    }

    uni.navigateBack({
      delta: 1,
    });
  } else {
    uni.switchTab({
      url: "/pages/index/index",
    });
  }
};
const codeChange = (text) => {
  tips.value = text;
};

const end = () => {
  console.log("end");
  canGetCode.value = true;
};
const start = () => {
  console.log("start");
  canGetCode.value = false;
};
</script>

<style scoped lang="scss">
.binding-phone-view {
  width: 100%;
  height: 100vh;
  position: relative;
  background: #FFFFFF;

  .background {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
  }
  .content-view {
	height: 100%;
    position: relative;
    z-index: 10;
    padding: 0 32rpx;
    display: flex;
    flex-direction: column;
  }

  .head {
    margin-top: 28rpx;

    .title-view {
      font-size: 52rpx;
      line-height: 52rpx;
      color: #333333;
      font-weight: bold;
      margin-bottom: 24rpx;
    }

    .text-view {
      font-size: 38rpx;
      margin-top: 28rpx;
      color: #333333;
      margin-bottom: 115rpx;
    }
  }

  .content {
    flex: 1;
    width: 100%;
    border-radius: 40rpx 40rpx 0 0;
    background-color: #ffffff;
    padding: 60rpx 40rpx;

    .label-view {
      display: flex;
      align-items: center;
      margin-bottom: 20rpx;

      .label-icon {
        width: 38rpx;
        height: 38rpx;
        margin-right: 8rpx;
      }

      .label-text {
        font-size: 28rpx;
        color: #626666;
        line-height: 28px;
      }
    }
  }

  .phone-view {
    display: flex;
    align-items: center;
    font-size: 28rpx;
    color: #333333;
    background-color: #f4f5f7;
    border-radius: 44rpx;
    height: 88rpx;
    padding: 0 36rpx;
    margin-bottom: 50rpx;

    .right-view {
      width: 100%;
    }
  }

  .code-view {
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 28rpx;
    color: #333333;
    background-color: #f4f5f7;
    border-radius: 44rpx;
    height: 88rpx;
    padding: 0 36rpx;
    margin-bottom: 140rpx;

    .middle-view {
      background-color: #5acee0;
      width: 2rpx;
      height: 32rpx;
      margin: 0 12rpx;
      flex-shrink: 0;
    }

    .left-view {
      width: 330rpx;
    }

    .right-view {
      font-weight: 400;
      width: 186rpx;
      height: 100%;
      display: flex;
      align-items: center;
      justify-content: flex-end;

      .active {
        color: #5acee0;
      }
    }
  }

  .bottom-vew {
    .button-text {
      color: #ffffff;
      height: 104rpx;
      line-height: 104rpx;
      font-weight: bold;
      font-size: 32rpx;
    }
  }

  .quick-title {
    margin-top: 40rpx;
    width: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    text-align: center;
    line-height: 28upx;
    font-size: 24upx;
    color: #8d8d8d;
    font-weight: 500;

    &-weight {
      font-weight: bold;
      color: #333333;
    }

    &-icon {
      width: 28upx;
      height: 28upx;
      border-radius: 50%;
      margin-right: 16upx;
      border: 2upx solid #333333;
      display: inline-block;
    }

    .icon-view {
      width: 32rpx;
      height: 32rpx;
      border-radius: 50%;
      border: 2rpx solid #626666;
      display: flex;
      justify-content: center;
      align-items: center;
      margin-right: 12rpx;

      .icon-agree {
        width: 16rpx;
        height: 16rpx;
        border-radius: 50%;
        background-color: #626666;
      }
    }

    .name-text {
      color: #5acee0;
    }
  }
}
</style>
